import 'package:flutter/material.dart';
import 'package:management/model/visit_matter_model.dart';

///修改来访事项
class SetVisitMatters extends StatefulWidget {
  final List<VisitMatter>? matterSource;

  const SetVisitMatters({Key? key, required this.matterSource}) : super(key: key);

  @override
  _SetVisitMattersState createState() => _SetVisitMattersState();
}

class _SetVisitMattersState extends State<SetVisitMatters> {
  late List<VisitMatter> matterSource;

  @override
  void initState() {
    super.initState();
    if (widget.matterSource == null) {
      matterSource = [];
    } else {
      matterSource = widget.matterSource!;
    }
  }

  @override
  void dispose() {
    VisitMatterProvider().close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("来访事项"),
      ),
      body: _buildBody(),
    );
  }

  _buildBody() {
    return SingleChildScrollView(
      child: Container(
        child: PaginatedDataTable(
          header: Divider(),
          actions: [
            IconButton(
                onPressed: () {
                  addMatter(context);
                },
                icon: Icon(
                  Icons.add,
                  size: 50,
                )),
            IconButton(
                onPressed: () {
                  deleteMatter();
                },
                icon: Icon(
                  Icons.delete,
                  size: 50,
                )),
          ],
          columns: [DataColumn(label: Text("名称"))],
          source: VisitMattersDataSource(matterSource),
          onSelectAll: (all) {
            setState(() {
              matterSource.forEach((element) {
                element.selected = all;
              });
            });
          },
        ),
      ),
    );
    ;
  }

  void addMatter(BuildContext context) {
    final TextEditingController matterCtl = TextEditingController();
    GlobalKey<FormState> key = GlobalKey();
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            content: SingleChildScrollView(
              child: Form(
                key: key,
                child: Container(
                  width: 100,
                  height: 60,
                  child: TextFormField(
                    controller: matterCtl,
                    validator: (value) {
                      if (value!.isEmpty) {
                        return "不能为空";
                      }
                      return null;
                    },
                    decoration: InputDecoration(hintText: "请输入来访事项"),
                  ),
                ),
              ),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    key.currentState!.save();
                    if (key.currentState!.validate()) {
                      matterSource.add(VisitMatter(matterCtl.text));
                      VisitMatterProvider().insert(VisitMatter(matterCtl.text));
                      setState(() {});
                      Navigator.pop(context);
                    }
                  },
                  child: Text("添加")),
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("取消")),
            ],
          );
        });
  }

  void deleteMatter() async {
    List<VisitMatter> deleteMatters = [];
    matterSource.forEach((element) {
      if (element.selected!) {
        deleteMatters.add(element);
      }
    });
    var visitMatterProvider = VisitMatterProvider();
    await visitMatterProvider.open();
    deleteMatters.forEach((element) {
      visitMatterProvider.delete(element);
      matterSource.remove(element);
    });

    setState(() {});
  }
}

class VisitMattersDataSource extends DataTableSource {
  final List<VisitMatter> data;

  VisitMattersDataSource(this.data);

  @override
  DataRow? getRow(int index) {
    if (index > data.length) {
      return null;
    }
    return DataRow.byIndex(
        index: index,
        cells: [
          DataCell(Text(
            data[index].matter!,
            style: TextStyle(fontSize: 30, fontStyle: FontStyle.italic),
          ))
        ],
        selected: data[index].selected!,
        onSelectChanged: (selected) {
          data[index].selected = selected;
          notifyListeners();
        });
  }

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => data.length;

  @override
  int get selectedRowCount => 0;
}
